package com.sharding.transaction.algorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;

public class OrderTableShardingRangeAlgorithm implements RangeShardingAlgorithm<Date> {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Date> shardingValue) {

        //preciseShardingValue就是当前插入的字段值
        //collection 内就是所有的逻辑表
        //获取字段值
//        LocalDateTime time = preciseShardingValue.getValue();
//        return "orders_" + (time.getMonth().getValue() - 1);
        SimpleDateFormat format = new SimpleDateFormat("MM");
//        return "orders_" + (Integer.valueOf(format.format(shardingValue.getValue())) - 1);


        Range<Date> valueRange = shardingValue.getValueRange();

        Date lowerDate = valueRange.lowerEndpoint();
        Date uperDate = valueRange.upperEndpoint();

        LinkedHashSet<String> collection = new LinkedHashSet<>();

        Integer lowerYear = Integer.valueOf(new SimpleDateFormat("YYYY").format(lowerDate));
        Integer uperYear = Integer.valueOf(new SimpleDateFormat("YYYY").format(uperDate));
        while(lowerYear <= uperYear){
            collection.add("orders_" + (Integer.valueOf(format.format(lowerDate)) - 1));
            lowerYear ++;
        }
        return collection;
    }
}
